<template>
  <div class="msgCode">
    <button v-if="showCodeBtn" type="button" @click="toGetCode">
      获取验证码
    </button>
    <button v-else type="button" disabled>{{ count }}秒</button>
  </div>
</template>

<script>
import { getCode } from '@/api/users';

export default {
  props: ['phoneNumber', 'isCheck'],
  data () {
    return {
      showCodeBtn: true,
      count: null,
    }
  },
  created () {
  },
  mounted () {
  },
  methods: {
    setCountDown () { // 倒计时
      this.count = 60;
      this.showCodeBtn = false;
      let timer = setInterval(() => {
        this.count--;
        if (this.count === 0) {
          this.showCodeBtn = true;
          this.count = null;
          clearInterval(timer);
          timer = null;
        }
      }, 1000);
    },
    toGetCode () {
      const mobile = this.phoneNumber || '';
      if (!mobile || !/^1[3456789]\d{9}$/.test(mobile)) {
        this.$alertWarn('请先正确填写手机号码！')
        return false
      }
      // 倒计时
      this.setCountDown();
      const paramObj = {
        mobile
      }
      if (this.isCheck) {
        paramObj.type = 1;
      }
      getCode(paramObj).then(res => {
        if (res.code === 200) {
          this.$alertSuc(res.msg);
        } else {
          this.$alertErr(res.msg || '网络错误, 稍后再试！');
        }
      }).catch(err => {
        console.log(err)
        this.$alertErr(err || '网络错误, 稍后再试！');
      })
    },
  }
}
</script>
<style lang="stylus" scoped>
.msgCode {
  position: absolute;
  top: 10px;
  right: 0;
  width: 135px;
  height: 35px;
  button {
    width: 100%;
    height: 100%;
    border: 1px solid $color-main;
    background: #fff;
    border-radius: 4px;
    color: $color-main;
  }
}
</style>
